<template>
  <div class="page-view">
    <ul class="my-entry-list">
      <!-- 个人中心 -->
      <li
        class="my-entry"
        :class="{'has-realname': userRealName !== ''}"
        @click="onChgRealName"
      >
        <span class="entry-name">
          姓名
        </span>
        <span class="entry-info">
          {{ userRealName || '请输入真实姓名' }}
        </span>
        <van-icon name="arrow" />
      </li>
      <router-link
        class="my-entry"
        :to="{name: 'changePhone'}"
        tag="li"
      >
        <span class="entry-name">
          手机号码
        </span>
        <span class="entry-info">
          {{ userPhone }}
        </span>
        <van-icon name="arrow" />
      </router-link>
      <!-- 身份证信息 -->
      <li class="my-entry prompt-text no-border">
        <span>身份信息</span>
        <van-uploader
          accept="image/*"
          :max-size="20971520"
          :after-read="onReadCardFront"
          @oversize="overSize"
        >
          （<span class="btn-card-text">点击上传身份证后自动填写</span>）
        </van-uploader>
      </li>
      <!-- 信息 -->
      <router-link
        class="my-entry no-border"
        :to="{name: 'changeSex'}"
        tag="li"
      >
        <span class="entry-name">
          性别
        </span>
        <span
          class="entry-info"
        >
          {{ sexArray[userMoreInfo.SexType] }}
        </span>
        <van-icon name="arrow" />
      </router-link>
      <li
        class="my-entry"
        @click="onShowPopup(5, 'Nation')"
      >
        <span class="entry-name">
          民族
        </span>
        <span class="entry-info">
          {{ userMoreInfo.Nation }}
        </span>
        <van-icon name="arrow" />
      </li>
      <li
        class="my-entry"
        @click="onShowPopupBirth"
      >
        <span class="entry-name">
          出生日期
        </span>
        <span class="entry-info">
          {{ userMoreInfo.Birthday }}
        </span>
        <van-icon name="arrow" />
      </li>
      <router-link
        :to="{name: 'chgMoreInfo', query: {
          type: '5',
          title: '修改居住地',
          content: userMoreInfo.Address
        }}"
        tag="li"
        class="my-entry"
      >
        <span class="entry-name">
          居住地
        </span>
        <span class="entry-info">
          {{ userMoreInfo.Address.length > 12 ?
            userMoreInfo.Address.substring(0, 12) + '...' : userMoreInfo.Address }}
        </span>
        <van-icon name="arrow" />
      </router-link>
      <router-link
        class="my-entry"
        :to="{name: 'changeCardNo'}"
        tag="li"
      >
        <span class="entry-name">
          身份证号
        </span>
        <span class="entry-info">
          {{ userMoreInfo.CardNo }}
        </span>
        <van-icon name="arrow" />
      </router-link>
      <!-- 其他信息 -->
      <li class="my-entry prompt-text no-border">
        身份信息
      </li>
      <li
        class="my-entry no-border"
        @click="onShowPopup(6, 'MaritalStatus')"
      >
        <span class="entry-name">
          婚姻状况
        </span>
        <span
          v-if="getMoreInfoSuccess"
          class="entry-info"
        >
          {{ userMoreInfo.MaritalStatus === '2' ? '' :
            (userMoreInfo.MaritalStatus === '1' ? '已婚' : '未婚') }}
        </span>
        <van-icon name="arrow" />
      </li>
      <li
        class="my-entry"
        @click="onShowPopup(7, 'Political')"
      >
        <span class="entry-name">
          政治面貌
        </span>
        <span class="entry-info">
          {{ userMoreInfo.Political }}
        </span>
        <van-icon name="arrow" />
      </li>
      <router-link
        :to="{name: 'chgMoreInfo', query: {
          type: '1',
          title: '修改工作单位',
          content: userMoreInfo.WorkUnit
        }}"
        tag="li"
        class="my-entry"
      >
        <span class="entry-name">
          工作单位
        </span>
        <span class="entry-info">
          {{ userMoreInfo.WorkUnit.length > 12 ?
            userMoreInfo.WorkUnit.substring(0, 12) + '...' : userMoreInfo.WorkUnit }}
        </span>
        <van-icon name="arrow" />
      </router-link>
      <router-link
        :to="{name: 'chgMoreInfo', query: {
          type: '2',
          title: '修改通信地址',
          content: userMoreInfo.MailingAddress
        }}"
        tag="li"
        class="my-entry"
      >
        <span class="entry-name">
          通信地址
        </span>
        <span class="entry-info">
          {{ userMoreInfo.MailingAddress.length > 12 ?
            userMoreInfo.MailingAddress.substring(0, 12) + '...' : userMoreInfo.MailingAddress }}
        </span>
        <van-icon name="arrow" />
      </router-link>
      <li
        class="my-entry"
        @click="onShowPopup(8, 'Education')"
      >
        <span class="entry-name">
          最高学历
        </span>
        <span class="entry-info">
          {{ userMoreInfo.Education }}
        </span>
        <van-icon name="arrow" />
      </li>
      <router-link
        :to="{name: 'chgMoreInfo', query: {
          type: '3',
          title: '修改毕业院校',
          content: userMoreInfo.GraduateCollege
        }}"
        tag="li"
        class="my-entry"
      >
        <span class="entry-name">
          毕业院校
        </span>
        <span class="entry-info">
          {{ userMoreInfo.GraduateCollege.length > 12 ?
            userMoreInfo.GraduateCollege.substring(0, 12) + '...' : userMoreInfo.GraduateCollege }}
        </span>
        <van-icon name="arrow" />
      </router-link>
      <li
        class="my-entry"
        @click="onShowPopup(9, 'GraduateTimeStr')"
      >
        <span class="entry-name">
          毕业时间
        </span>
        <span class="entry-info">
          {{ userMoreInfo.GraduateTimeStr }}
        </span>
        <van-icon name="arrow" />
      </li>
      <router-link
        :to="{name: 'chgMoreInfo', query: {
          type: '4',
          title: '修改毕业证书编号',
          content: userMoreInfo.CertificateNo
        }}"
        tag="li"
        class="my-entry"
      >
        <span class="entry-name">
          毕业证书编号
        </span>
        <span class="entry-info">
          {{ userMoreInfo.CertificateNo.length > 12 ?
            userMoreInfo.CertificateNo.substring(0, 12) + '...' : userMoreInfo.CertificateNo }}
        </span>
        <van-icon name="arrow" />
      </router-link>
    </ul>
    <!-- 上拉菜单选择 -->
    <van-popup
      v-model="isShowPopup"
      position="bottom"
    >
      <van-picker
        v-if="!isShowDatePicker"
        ref="picker"
        show-toolbar
        :columns="columns"
        @cancel="onCancel"
        @confirm="onConfirm"
      />
      <van-datetime-picker
        v-if="isShowDatePicker"
        v-model="currentDate"
        type="date"
        :max-date="maxdate"
        :min-date="mindate"
        :formatter="formatter"
        @confirm="onConfirm"
        @cancel="onCancel"
      />
    </van-popup>
    <!-- 上传图片 -->
    <div class="upload-div">
      <!-- 11111 -->
      <div class="img-div">
        <div
          v-if="userMoreInfo.IdentityCardFront === ''"
          class="upload-text"
        >
          <van-uploader
            accept="image/*"
            :max-size="20971520"
            :after-read="onReadCardFront"
            @oversize="overSize"
          >
            <img
              class="add-img-icon"
              src="~assets/mine/add-img.png"
            >
            <p>上传身份证正面</p>
          </van-uploader>
        </div>
        <div
          v-else
          class="has-img"
        >
          <img
            class="img-content"
            :src="userMoreInfo.IdentityCardFront"
            @click="onImagePreview('IdentityCardFront')"
          >
          <van-icon
            name="close"
            size="20px"
            class="icon-close"
            @click="onDelImage(10, 'IdentityCardFront')"
          />
        </div>
      </div>
      <!-- 222222 -->
      <div class="img-div">
        <div
          v-if="userMoreInfo.IdentityCardReverse === ''"
          class="upload-text"
        >
          <van-uploader
            accept="image/*"
            :max-size="20971520"
            :after-read="onReadCardReverse"
            @oversize="overSize"
          >
            <img
              class="add-img-icon"
              src="~assets/mine/add-img.png"
            >
            <p>上传身份证反面</p>
          </van-uploader>
        </div>
        <div
          v-else
          class="has-img"
        >
          <img
            class="img-content"
            :src="userMoreInfo.IdentityCardReverse"
            @click="onImagePreview('IdentityCardReverse')"
          >
          <van-icon
            name="close"
            size="20px"
            class="icon-close"
            @click="onDelImage(11, 'IdentityCardReverse')"
          />
        </div>
      </div>
    </div>
    <div class="upload-div padding-bot">
      <!-- 33333 -->
      <div class="img-div">
        <div
          v-if="userMoreInfo.CardPhoto === ''"
          class="upload-text"
        >
          <van-uploader
            accept="image/*"
            :max-size="20971520"
            :after-read="onReadCardPhoto"
            @oversize="overSize"
          >
            <img
              class="add-img-icon"
              src="~assets/mine/add-img.png"
            >
            <p>上传证件照</p>
          </van-uploader>
        </div>
        <div
          v-else
          class="has-img"
        >
          <img
            class="img-content"
            :src="userMoreInfo.CardPhoto"
            @click="onImagePreview('CardPhoto')"
          >
          <van-icon
            name="close"
            size="20px"
            class="icon-close"
            @click="onDelImage(12, 'CardPhoto')"
          />
        </div>
      </div>
      <!-- 44444 -->
      <div class="img-div">
        <div
          v-if="userMoreInfo.GraduationCertificate === ''"
          class="upload-text"
        >
          <van-uploader
            accept="image/*"
            :max-size="20971520"
            :after-read="onReadCertificate"
            @oversize="overSize"
          >
            <img
              class="add-img-icon"
              src="~assets/mine/add-img.png"
            >
            <p>上传毕业证书</p>
          </van-uploader>
        </div>
        <div
          v-else
          class="has-img"
        >
          <img
            class="img-content"
            :src="userMoreInfo.GraduationCertificate"
            @click="onImagePreview('GraduationCertificate')"
          >
          <van-icon
            name="close"
            size="20px"
            class="icon-close"
            @click="onDelImage(13, 'GraduationCertificate')"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { mapState } from 'vuex'
import { SET_USER_INFO } from '@/store/mutations'
import { Picker, DatetimePicker, Uploader, ImagePreview } from 'vant'
import userInfo from '@/store/modules/userInfo'
export default Vue.extend({
  components: {
    'van-uploader': Uploader,
    'van-picker': Picker,
    'van-datetime-picker': DatetimePicker,
  },
  data () {
    let Mobile = this.$store.state.userInfo.Phone
    let realName = this.$store.state.userInfo.RealName
    return {
      userMoreInfo: {} as any,
      curType: 0,
      curTypeName: '',
      isShowPopup: false, // 是否显示上拉菜单选择
      isShowDatePicker: false, // 是否显示日期选择
      isChgBirth: false, // 是否修改生日
      currentDate: new Date(),
      maxdate: new Date(),
      mindate: new Date(1900, 0, 1),
      userPhone: Mobile.replace(/\s/g, '').replace(/(\d{3})(\d{0,4})(\d{0,4})/, '$1 $2 $3'),
      userRealName: realName.length > 10 ? realName.substring(0, 10) + '...' : realName,

      columns: [],
      sexArray: ['男', '女', ''],
      MaritalStatusName: ['未婚', '已婚'],
      basicData: {
        NationId: [],
        NationName: [],
        PoliticalId: [],
        PoliticalName: [],
        EducationId: [],
        EducationName: [],
      } as any,
      getMoreInfoSuccess: false,
    }
  },
  computed: mapState(['userInfo']),
  created () {
    this.getBaseData()
    this.getMoreInfoList()
  },
  methods: {
    // 获取民族、政治面貌、学历数据
    getBaseData () {
      this.$axios({
        url: 'User/GetMyIndexMoreInfoList',
        method: 'get',
      }).then(res => {
        this.$set(this.$data, 'basicData', res)
      })
    },
    // 获取用户更多信息
    getMoreInfoList () {
      this.$axios({
        url: 'User/GetMyIndexMoreInfoForH5',
        method: 'get',
      }).then(res => {
        this.getMoreInfoSuccess = true
        this.userMoreInfo = res
        this.$store.commit(SET_USER_INFO, {
          Birthday: res.Birthday,
          CardNo: res.CardNo,
        })
      })
    },
    formatter (type: any, value: any) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      }
      return value
    },
    // 展示上拉框弹出层
    onShowPopup (type: number, TypeName: string) {
      this.curType = type
      this.curTypeName = TypeName
      // 毕业时间popup
      if (type === 9) {
        this.currentDate = this.userMoreInfo.GraduateTimeStr
          ? new Date(this.userMoreInfo.GraduateTimeStr) : new Date()
        this.isShowDatePicker = true
      } else if (type === 6) {
        this.isShowDatePicker = false
        const curMarialIndex = +this.userMoreInfo.MaritalStatus
        this.$set(this.$data, 'columns', [{
          values: this.MaritalStatusName,
          defaultIndex: curMarialIndex,
        }])
      } else {
        this.isShowDatePicker = false
        const curIndex = this.getCurIndex(this.userMoreInfo[TypeName],
          this.basicData[TypeName + 'Name'])
        this.$set(this.$data, 'columns', [{
          values: this.basicData[TypeName + 'Name'],
          defaultIndex: curIndex,
        }])
      }
      this.isShowPopup = true
    },
    onConfirm (value: any, index ?: any) {
      console.log('value:', value, 'hhindex', index)
      if (this.isChgBirth) {
        this.onBirthdayConfirm(value)
        return
      }
      let content = ''
      if (this.curType === 6) {
        content = index[0]
      } else if (this.curType !== 9) {
        content = this.basicData[this.curTypeName + 'Id'][index]
      }
      this.$axios({
        url: 'Setting/UpdateMyIndexMoreInfoForH5',
        data: {
          Type: this.curType,
          Content: this.curType === 9 ? value : content,
        },
      }).then(res => {
        this.isShowPopup = false
        this.isShowDatePicker = false
        if (this.curType === 9) {
          this.userMoreInfo.GraduateTimeStr = this.getCurTimeStr(value)
        } else {
          this.userMoreInfo[this.curTypeName] = this.curType === 6 ? res.Content : value[0]
        }
        console.log('this.userMoreInfo[this.curTypeName]', this.userMoreInfo[this.curTypeName])
        this.$toast({ message: '更新成功！', duration: 1000 })
      })
    },
    onCancel () {
      this.isShowPopup = false
      this.isShowDatePicker = false
    },
    // 拼接毕业时间字符串
    getCurTimeStr (value: any) {
      const years = value.getFullYear()
      const monthTime = value.getMonth() + 1
      const months = monthTime < 10 ? '0' + monthTime : monthTime
      const dayTime = value.getDate()
      const days = dayTime < 10 ? '0' + dayTime : dayTime
      return years + '-' + months + '-' + days
    },
    // 获取选中数据的Index
    getCurIndex (val: any, column: any) {
      let i = 0
      if (val === '') {
        return i
      }
      for (i = 0; i < column.length; i++) {
        if (column[i] === val) {
          return i
        }
      }
    },
    overSize () {
      this.$toast('请上传大小不超过20M的图片！')
    },
    // 读取上传图片
    onReadCardFront (file: any) {
      this.uploadImg(file, 10, 'IdentityCardFront')
    },
    onReadCardReverse (file: any) {
      this.uploadImg(file, 11, 'IdentityCardReverse')
    },
    onReadCardPhoto (file: any) {
      this.uploadImg(file, 12, 'CardPhoto')
    },
    onReadCertificate (file: any) {
      this.uploadImg(file, 13, 'GraduationCertificate')
    },
    // 上传图片update
    uploadImg (file: any, type: number, name: string) {
      if (file.file.type !== 'image/png' &&
          file.file.type !== 'image/jpg' && file.file.type !== 'image/jpeg') {
        this.$toast('请上传格式为jpg或png的图片！')
        return
      }
      this.$toast.loading({
        message: '上传中...',
        duration: 0,
        className: 'toast-loading',
      })
      const commaPosition = file.content.indexOf(',') + 1
      const Content = file.content.substr(commaPosition)
      this.$axios({
        url: 'Setting/UpdateMyIndexMoreInfoForH5',
        data: {
          Type: type,
          Content,
        },
      }).then(res => {
        if (type === 10) {
          this.$toast.loading({
            message: '身份信息识别中...',
            duration: 0,
            className: 'toast-loading',
          })
          this.cardORC(type, name, res)
          return
        }
        this.userMoreInfo[name] = res
        this.$toast('上传成功！')
      })
    },
    // 识别身份证图片
    cardORC (type: number, name: string, imgUrl: string) {
      this.$axios({
        url: 'User/UserIDCardORC',
        data: {
          imgUrl,
          type: type === 10 ? 'FRONT' : 'BACK',
          NeedSaveDatabase: true,
        },
      }).then(data => {
        this.userMoreInfo.Birthday = data.Birth
        this.userMoreInfo.Address = data.Address
        this.userMoreInfo.Nation = data.Nation
        this.userMoreInfo.SexType = data.SexType
        this.userMoreInfo.CardNo = data.IdNum
        this.userMoreInfo[name] = imgUrl
        this.$toast('识别成功！')
      }, e => {
        this.$toast('识别失败，请重试！')
      })
    },
    // 删除上传的图片
    onDelImage (type: number, typeName: string) {
      this.$axios({
        url: 'Setting/UpdateMyIndexMoreInfoForH5',
        data: {
          Type: type,
          Content: '',
        },
      }).then(res => {
        this.$toast('删除成功！')
        this.userMoreInfo[typeName] = ''
      }, e => {
        this.$toast('删除失败！')
      })
    },
    // 预览图片
    onImagePreview (typeName: string) {
      ImagePreview([this.userMoreInfo[typeName]])
    },
    onChgRealName () {
      let realName = this.userInfo.RealName
      if (!realName) {
        this.$router.push({ name: 'changeRealName' })
      }
    },
    // 展示生日弹出层
    onShowPopupBirth () {
      let curBirthday = this.userMoreInfo.Birthday
      this.currentDate = curBirthday ? new Date(curBirthday) : new Date()
      this.isShowPopup = true
      this.isShowDatePicker = true
      this.isChgBirth = true
    },
    // 提交生日日期
    onBirthdayConfirm (value : any) {
      let userAge = new Date().getFullYear() - value.getFullYear()
      let userBirthday = this.getCurTimeStr(value)
      this.$axios({
        url: 'Setting/UpdateUserInfo',
        data: {
          Type: 5,
          Content: userBirthday,
        },
      }).then(res => {
        this.userMoreInfo.Birthday = userBirthday
        this.$store.commit(SET_USER_INFO, { Birthday: userBirthday, Age: userAge })
        this.$toast({ message: '更新成功！', duration: 1000 })
      })
      this.isShowPopup = false
      this.isShowDatePicker = false
      this.isChgBirth = false
    },
  },
})
</script>

<style lang="scss" scoped>
.my-entry-list {
  background: #fff;
  margin-bottom: 20px;
  + .my-entry-list {
    margin-top: 10px;
  }
  .prompt-text {
    background-color: #eee;
    font-size: 30px;
    margin-left: 0;
    display: flex;
    justify-content: center;
  }
}
.has-realname, .my-entry {
  display: flex;
  align-items: center;
  padding-right: 36px;
  margin-left: 40px;
  height: 109px;
  color: #333;
  + .my-entry {
    @include px1border(top, #e1e1e1)
  }
  .van-icon-arrow {
    font-size: 24px;
  }
}
.no-border {
  border: none !important;
}
.has-realname {
  color: #9e9e9e;
}
.entry-name {
  flex: 1;
  font-size: 30px;
}
.entry-info {
  font-size: 30px;
  padding-right: 20px;
}
.upload-div {
  background: #FFF;
  padding: 40px 40px 0px;
  display: flex;
  justify-content: space-between;
}
.img-div {
  position: relative;
  background: #F0F0F0;
  width: 324px;
  height: 182px;
}
.padding-bot {
  padding-bottom: 50px;
}
.upload-text {
  text-align: center;
  color: #999;
  font-size: 24px;
  line-height: 30px;
}
.add-img-icon {
  margin: 30px 0;
  width: 58px;
  height: 58px;
}
.icon-close {
  position: absolute;
  top: -15px;
  right: -15px;
  color: #999;
}
.has-img {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  vertical-align: middle;
}
.img-content {
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  max-width: 100%;
  max-height: 100%;
}
.btn-card-text {
  color: $primary-web;
}
</style>

<style>
.toast-loading {
  width: 3rem;
}
</style>
